package com.hh.xx.hive;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hive.service.auth.HiveAuthFactory;
import org.apache.hive.service.auth.PlainSaslHelper;
import org.apache.hive.service.cli.thrift.*;
import org.apache.hive.service.rpc.thrift.*;
import org.apache.hive.service.rpc.thrift.TOpenSessionReq;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportFactory;

import javax.security.auth.login.LoginException;
import javax.security.sasl.SaslException;
import java.util.Iterator;
import java.util.List;

/**
 * 纯的发thrift请求的方式, 参考的
 * https://gist.github.com/rajkrrsingh/4ab7153ca90969dcad21
 * to make it work add the hive-service dependencies
 * in pom.xml
 */
public class HiveThriftClient {
    public static void main(String[] args) throws Exception {
        HiveConf hiveConf = new HiveConf();
        hiveConf.addResource("/Users/tzp/Documents/env/apache-hive-3.1.2-bin/conf/hive-site.xml");
        TTransport transport = new TSocket("127.0.0.1", 10000);
//        HiveAuthFactory authFactory = new HiveAuthFactory(hiveConf);
//        TTransportFactory authTransFactory = authFactory.getAuthTransFactory();
//        transport = authTransFactory.getTransport(transport);
        transport = PlainSaslHelper.getPlainTransport("root", "xxx", transport);

        TBinaryProtocol protocol = new TBinaryProtocol(transport);
        TCLIService.Client client = new TCLIService.Client(protocol);

        transport.open();
        TOpenSessionReq openReq = new TOpenSessionReq();
        TOpenSessionResp openResp = client.OpenSession(openReq);
        TSessionHandle sessHandle = openResp.getSessionHandle();

        TExecuteStatementReq execReq = new TExecuteStatementReq(sessHandle, "select * from u_data_ex limit 2");
        TExecuteStatementResp execResp = client.ExecuteStatement(execReq);
        TOperationHandle stmtHandle = execResp.getOperationHandle();

        TFetchResultsReq fetchReq = new TFetchResultsReq(stmtHandle, TFetchOrientation.FETCH_FIRST, 100);
        TFetchResultsResp resultsResp = client.FetchResults(fetchReq);
        List<TColumn> res = resultsResp.getResults().getColumns();
        for (TColumn tCol : res) {
            System.out.println(tCol.getFieldValue().toString());
        }

        TCloseOperationReq closeReq = new TCloseOperationReq();
        closeReq.setOperationHandle(stmtHandle);
        client.CloseOperation(closeReq);
        TCloseSessionReq closeConnectionReq = new TCloseSessionReq(sessHandle);
        client.CloseSession(closeConnectionReq);

        transport.close();
    }

}